/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
class Promise {
    constructor(executor) {
        // 执行器异常
        try {
            executor(this.resolve, this.reject);
        } catch (error) {
            this.reject(error);
        }
    }

    status = PENDING;
    value = undefined;
    reason = undefined;
    // 保存成功的回调，当多个then时 是数组
    // successCallback = undefined;
    successCallback = [];
    // 保存失败的回调
    // failCallback = undefined;
    failCallback = [];
    resolve = (value) => {
        // 判断是否时pending状态
        if (this.status !== PENDING) return;
        this.status = FULFILLED;
        this.value = value;
        // 判断成功回调是否存在
        // this.successCallback && this.successCallback(this.value)
        // while (this.successCallback.length) this.successCallback.shift()(this.value)
        while (this.successCallback.length) this.successCallback.shift()();
    };

    reject = (reason) => {
        // 判断是否时pending状态
        if (this.status !== PENDING) return;

        this.status = REJECTED;
        this.reason = reason;
        // 判断失败回调是否存在
        // this.failCallback && this.failCallback(this.reason)
        // while (this.failCallback.length) this.failCallback.shift()(this.reason)
        while (this.failCallback.length) this.failCallback.shift()();
    };

    then(successCallback, failCallback) {
        // 判断是否有参数
        successCallback = successCallback ? successCallback : (value) => value;
        failCallback = failCallback ?
            failCallback :
            (reason) => {
                throw reason;
            };
        // then方法链式调用， 需要返回的也是一个Promise对象才可以
        let promise2 = new Promise((resolve, reject) => {
            if (this.status === FULFILLED) {
                try {
                    // 为了访问到promise2，所以采用异步操作，时间设置为0
                    setTimeout(() => {
                        //成功的返回值，传给下一个then的成功参数
                        let x = successCallback(this.value);
                        // resolve(x)
                        resolvePromise(promise2, x, resolve, reject);
                    }, 0);
                } catch (error) {
                    reject(error);
                }
            } else if (this.status === REJECTED) {
                try {
                    // 为了访问到promise2，所以采用异步操作，时间设置为0
                    setTimeout(() => {
                        //成功的返回值，传给下一个then的成功参数
                        let x = failCallback(this.reason);
                        // resolve(x)
                        resolvePromise(promise2, x, resolve, reject);
                    }, 0);
                } catch (error) {
                    reject(error);
                }
            } else {
                // 等待状态时，保存成功和失败的回调
                // this.successCallback = successCallback;
                // this.failCallback = failCallback;
                // this.successCallback.push(successCallback)
                // this.failCallback.push(failCallback)
                this.successCallback.push(() => {
                    try {
                        // 为了访问到promise2，所以采用异步操作，时间设置为0
                        setTimeout(() => {
                            //成功的返回值，传给下一个then的成功参数
                            let x = successCallback(this.value);
                            // resolve(x)
                            resolvePromise(promise2, x, resolve, reject);
                        }, 0);
                    } catch (error) {
                        reject(error);
                    }
                });
                this.failCallback.push(() => {
                    try {
                        // 为了访问到promise2，所以采用异步操作，时间设置为0
                        setTimeout(() => {
                            //成功的返回值，传给下一个then的成功参数
                            let x = failCallback(this.reason);
                            // resolve(x)
                            resolvePromise(promise2, x, resolve, reject);
                        }, 0);
                    } catch (error) {
                        reject(error);
                    }
                });
            }
        });
        return promise2;
    }

    finally(callback) {
        // 返回的也是一个promise对象
        return this.then(
            (value) => {
                // 成功
                return Promise.resolve(callback()).then(() => value);
            },
            (reason) => {
                // 失败
                return Promise.resolve(callback()).then(() => {
                    throw reason;
                });
            }
        );
    }

    //catch方法，成功回调定义为undefined
    catch (failCallback) {
        return this.then(undefined, failCallback);
    }

    static all(array) {
        let result = [];
        let index = 0;
        return new Promise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value;
                index++;
                if (index === array.length) {
                    //所有的都执行完毕
                    resolve(result);
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i];
                if (current instanceof Promise) {
                    // promise对象，先执行
                    current.then(
                        (value) => addData(i, value),
                        (reason) => reject(reason)
                    );
                } else {
                    // 普通值
                    addData(i, array[i]);
                }
            }
        });
    }

    static resolve(value) {
        if (value instanceof Promise) return value;
        return new Promise((resolve, reject) => {
            resolve(value);
        });
    }
}

function resolvePromise(promise2, x, resolve, reject) {
    if (promise2 === x) {
        //链式调用自返回，抛出异常
        reject(new TypeError("Chaining cycle detected for promise #<Promise>"));
    }
    // 判断x的类型， 是Promise对象， 还是一个普通值
    if (x instanceof Promise) {
        // Promise对象
        x.then(resolve, reject);
    } else {
        // 普通值
        resolve(x);
    }
}